<%@page import="classes.LifebookImageSearchParameters"%>
<%@page import="classes.LifebookImage"%>
<%@page import="classes.DB"%>
<%@page import="classes.LifebookUser"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
        <link href="css/styles.css" rel="stylesheet">
        <link href="bootstrap-lightbox/bootstrap-lightbox.css" rel="stylesheet">
    </head>
    <body style ="background-image:url('bg.png')">
        <%
            LifebookUser user = (LifebookUser) session.getAttribute("user");
            if (user == null) {
                response.sendRedirect("index.jsp");
            } else {
                DB.cleanTempUploadsByUser(user.getUsername(), -1);
            }
        %>
        <div class="navbar">
            <div class="navbar-inner">
                <a class="brand" href="#"><b class ="life">Life</b><b class = "book">Book</b></a>
                <ul class="nav">
                    <li class="active"><a href ="browse.jsp"><span class ="navbarText"><i class = "icon-home icon-white"></i> Home</span></a></li>
                    <li><a href ="users.jsp"><span class ="navbarText"><i class = "icon-user icon-white"></i> Users</span></a></li>
                    <li><a href ="users/<%=user.getUsername()%>"><span class ="navbarText"><i class = "icon-list-alt icon-white"></i> Profile</span></a></li>
                </ul>
                <a href="#modal-upload" class="btn btn-success" data-toggle="modal"><i class="icon-upload icon-white"></i>Upload Image</a>
                <button class="btn pull-right btn-success" onClick ="location.href = 'LogoutServlet';">Logout</button>
                <a href="#advanceSearchModal" role="button" class="btn pull-right btn-success" data-toggle="modal"><i class = "icon-zoom-in icon-white"></i></a>
                <form class="navbar-search pull-right" action ="BrowseSimpleSearchServlet">
                    <input name ="browseSearchTerm" type="text" class="search-query input-xlarge" placeholder="Title, Tag, Category, Username, Pin Info">
                </form>
            </div>
        </div>

        <div class = "container">
            <ul class="breadcrumb">
                <li><b>Welcome <%=user.getUsername()%>!</b><span class="divider">/</span></li>
                <li><a href="browse.jsp">Popular Images</a> <span class="divider">/</span></li>
                <li><a href="ChangeBrowseTypeServlet?browseType=newimages">Recent Images</a> <span class="divider">/</span></li>
                <li><a href="ChangeBrowseTypeServlet?browseType=newsfeed">Personal Feed</a> <span class="divider">/</span></li>
                <!--<li><a href="ChangeBrowseTypeServlet?browseType=followed">Followed Users</a> <span class="divider">/</span></li> -->
            </ul>
            <div class = "container-fluid">
                <div id = "myMasonryContainer" 
                     class="masonry js-masonry offset">

                    <%
                        LifebookImageSearchParameters searchParameters = (LifebookImageSearchParameters) session.getAttribute("browseSearchParameters");
                        for (LifebookImage image : DB.getImages(searchParameters)) {
                            float imageHeight = (float) image.getHeight() / (float) image.getWidth() * (float) 180.0;
                            boolean hasTitle = true;
                            if (image.getImageTitle() == null || image.getImageTitle().trim().isEmpty()) {
                                hasTitle = false;
                            }
                    %>
                    <!--Image Thumbnail-->
                    <div style ="width:220px; 
                         height: <%=imageHeight + 40 + (hasTitle ? 10 : 0)%>px;">
                        <center>
                        <div style ="width:200px; 
                             height: <%=imageHeight + 20 + (hasTitle ? 10 : 0)%>px;
                             background-color:white;
                             border:1px solid #DADADA;">
                            <center>
                                <img 
                                    style ="
                                    width:180px; 
                                    height: <%=imageHeight%>px;
                                    position: relative;
                                    top: 10px;
                                    border:1px solid #E9E9E9;"
                                    src="images/<%=image.getImageID()%>" 
                                    Title="<%=image.getImageTitle()%>"
                                    onClick ="openImageModal(
                                '<%=image.getImageID()%>', '<%=image.getWidth()%>', '<%=image.getHeight()%>', '<%=image.getImageTitle()%>',
                                '<%=image.getImageCaption()%>', '<%=image.getLikes()%>', '<%=image.getOwnerUsername()%>');">
                            </center>
                        </div>
                            <b class = "imageTitle"
                               style =
                               "position: relative;
                               bottom:20px;"><%=image.getImageTitle() != null ? image.getImageTitle() : ""%></b>
                        </center>
                    </div>
                    <%
                        }
                        session.setAttribute("browseSearchParameters", new LifebookImageSearchParameters());
                    %>
                </div>

                <!-- View Image Modal-->
                <div id="imageViewModal" class="modal hide fade upload" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                    <div class="modal-header">
                        <center>
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h2 id ="viewTitle"style ="display:inline;" id="myModalLabel">Title</h2> <a id = "openUserButton" onClick = "openUserModal();" data-toggle ="modal"><h4 id ="viewUser" style ="display:inline;">by Username</h4></a>
                            <h4 id = "viewCaption">Caption</h4>
                        </center>
                    </div>
                    <div class="modal-body upload">
                        <center>
                            <div id ="imageCanvas"></div>
                        </center>
                    </div>
                    <div class="modal-footer">
                        <center>
                            <button onClick="likeImage(new Boolean(true));" id ="viewLikeButton" class="btn btn-large"><i id ="likeIcon" class="icon-heart"></i><span id="likeCounter"></span></button>
                            <button class="btn btn-large btn-inverse" data-dismiss="modal" aria-hidden="true">Close</button>
                            <button id ="deleteButton" class="btn btn-danger btn-large pull-right" hidden="true" href="#deactivatePhotoModal" data-toggle="modal"><i class="icon-white icon-trash"></i></button>
                        </center>
                    </div>
                </div>

                <!-- Deactivate Photo Modal -->
                <div id="deactivatePhotoModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                    <div class="modal-header">
                        <center>
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h3 id="myModalLabel">Confirm Deactivation</h3>
                        </center>
                    </div>
                    <div class="modal-body">
                        <center><h4>Are you sure that you want to delete the photo?</h4></center>
                    </div>
                    <div class="modal-footer">
                        <center>
                            <div class ="row">
                                <button class = "btn btn-large btn-primary input-xlarge" data-dismiss="modal" aria-hidden="true">I don't want to</button>
                            </div>
                            <div class ="row">
                                <button class = "btn btn-mini btn-danger" onClick="deletePhoto();">Yes</button>
                            </div>
                        </center>
                    </div>
                </div>

                <!--Modal for user-->
                <div id ="userModal" class = "modal hide fade">
                    <div class ="modal-header">
                        <a class="close" data-dismiss="modal">&times;</a>
                        <center>
                            <a id ="userModalProfileLink" href = "#"><h1 id = "userModalUsername" >Username</h1></a>
                        </center>
                    </div>
                    <div id ="userBody" class="modal-body">
                        <center>
                            <img id ="userModalImage" width ="300" src ="noProfileImage.png" class = "thumbnail">
                            <h5 class ='well' id ="userModalAboutMe">This is my Description</h5>
                        </center>
                    </div>
                    <div id ="userFooter" class="modal-footer">
                        <center>
                            <button onClick="followUser();" id ="followUserButton" class="btn btn-danger"><i id ="userLikeIcon" class="icon-white icon-heart"></i> <span id="isFollowingUserSpan"></span></button>
                            <button class = "btn btn-inverse" data-dismiss="modal" aria-hidden="true">Close</button>
                        </center>
                    </div>
                </div>

                <!-- Modal for Upload -->
                <div id="modal-upload" class="modal upload modal-image hide fade" tabindex="-1">
                    <div class="modal-header">
                        <a class="close" data-dismiss="modal">&times;</a>
                        <div>
                            <center>
                                Title: <input id ="uploadTitle" name = "title" class = "input-xlarge" type="text" placeholder="Title">
                                Caption: <input id ="uploadCaption" name = "caption" class = "input-xxlarge" type="text" placeholder="Caption">
                                <br/>
                                <b>To add a pin ,click anywhere on the image. To delete a pin, click on it.</b><br/>
                            </center>
                        </div>
                    </div>
                    <div class="modal-body upload">
                        <iframe src="uploadImage.jsp" seamless width ="100%" height = "100%"></iframe>
                    </div>
                    <div class="modal-footer">
                        <center>
                            <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
                            <button class="btn btn-primary" onClick ="uploadImage();"><i class="icon-ok icon-white"></i>Submit</button>
                        </center>
                    </div>
                </div>

                <!-- Advance Search -->
                <div height ="100%" id="advanceSearchModal" class="modal hide fade search" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                    <div class="modal-header">
                        <center>
                            <h1>Advance Search</h1>
                        </center>
                    </div>
                    <form action ="BrowseAdvanceSearchServlet">
                        <div class="modal-body search">
                            <center>
                                <h4>Title:</h4>
                                <input name ="title" type ="text">
                                <h4>Tag:</h4>
                                <input name ="tag" type ="text">
                                <h4>Pin Category:</h4>
                                <select name ="pinCategory">
                                    <option></option>
                                    <%
                                        for (String category : DB.getCategories()) {
                                    %>
                                    <option><%=category%></option>
                                    <%                                      }
                                    %>
                                </select>
                                <h4>Pin Info:</h4>
                                <input name ="pinInfo" type ="text">
                                <h4>Username:</h4>
                                <input name ="username" type ="text">
                                <h4>Get Results From:</h4>
                                <select name ="followerOrFollowing">
                                    <option>All users</option>
                                    <option>Users you follow</option>
                                    <option>Users who follow you</option>
                                </select>
                            </center>
                        </div>
                        <div class="modal-footer">
                            <center>
                                <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
                                <button type ="submit" class="btn btn-primary"><i class = "icon-zoom-in icon-white"></i>Search</button>
                            </center>
                        </div>
                    </form>
                </div>

                <!-- View Pin Modal -->
                <div id ="viewPinModal" class="modal hide">
                    <div class="modal-body">
                        <div class ="span3 offset1">
                            <h4>Pin Info:</h4>
                            <h5 id ="viewPinInfo" class ="well well-small"></h5>
                            <h4>Category:</h4> 
                            <h5 id ="viewPinCategory" class ="well well-small"></h5>
                            <h4>Tags</h4>
                            <h5 id ="viewPinTags" class ="well well-small"></h5>
                            <center>
                                <a onclick="browseRelatedPins($('#viewPinCategory').html(), $('#viewPinTags').html());"><h4>Browse related pins</h4></a>
                            </center>
                            <input type ="hidden" id ="viewPinID">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <center>
                            <button onClick="viewLikePin($('#viewPinID').val());" id ="viewPinLikeButton" class="btn btn-small"><i id ="viewPinLikeIcon" class="icon-heart"></i><span id="viewPinLikeCounter"></span></button>
                            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
                        </center>
                    </div>
                </div>

                <!-- Edit Pin Modal -->
                <div id ="editPinModal" class="modal hide">
                    <div class="modal-body">
                        <center>
                            <h4>Pin Info:</h4> <input id ="editPinInfo" type="text" class ="input-xlarge" placeholder="This is my Ferrari">
                            <h4>Category:</h4> 
                            <select id = "editPinCategory" class ="input-xlarge">
                                <%
                                    for (String category : DB.getCategories()) {
                                %>
                                <option><%=category%></option>
                                <%                            }
                                %>
                            </select>
                            <h4>Tags (Separated by a comma):</h4> <input id ="editPinTag" type="text" class ="input-xlarge" placeholder="ferrari, dynamite fishing, yolo">
                            <a onclick="browseRelatedPins($('#editPinCategory').val(), $('#editPinTag').val());"><h4>Browse related pins</h4></a>
                            <input type ="hidden" id ="editPinID">
                        </center>
                    </div>
                    <div class="modal-footer">
                        <center>
                            <button onClick="editLikePin($('#editPinID').val());" id ="editPinLikeButton" class="btn btn-small"><i id ="editPinLikeIcon" class="icon-heart"></i><span id="editPinLikeCounter"></span></button>
                            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
                            <button class="btn btn-success" onClick ="confirmEdit($('#editPinInfo').val(),
                                $('#editPinCategory').val(), $('#editPinTag').val(), $('#editPinID').val());">Edit Pin</button>
                            <button id ="deleteButton" class="btn btn-danger btn-small pull-right" 
                                    onClick="$('#deletePinModal').modal('show');"><i class="icon-white icon-trash"></i></button>
                        </center>
                    </div>
                </div>

                <!-- Delete Pin Modal -->
                <div id="deletePinModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                    <div class="modal-header">
                        <center>
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h3 id="myModalLabel">Confirm Deactivation</h3>
                        </center>
                    </div>
                    <div class="modal-body">
                        <center><h4>Are you sure that you want to delete the pin?</h4></center>
                    </div>
                    <div class="modal-footer">
                        <center>
                            <div class ="row">
                                <button class = "btn btn-large btn-primary input-xlarge" data-dismiss="modal" aria-hidden="true">I don't want to</button>
                            </div>
                            <div class ="row">
                                <button class = "btn btn-mini btn-danger" 
                                        onClick="$('#deletePinModal').modal('hide'),
                                $('#editPinModal').modal('hide'),
                                deletePin($('#editPinID').val());">Yes</button>
                            </div>
                        </center>
                    </div>
                </div>

                <!-- Add Pin Edit Mode Modal -->
                <div height ="100%" id="addPinEditModal" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                    <div class="modal-body">
                        <center>
                            <h4>Pin Info:</h4> <input id ="addPinEditInfo" type="text" class ="input-xlarge" placeholder="This is my Ferrari">
                            <h4>Category:</h4> 
                            <select id = "addPinEditCategory" class ="input-xlarge">
                                <%
                                    for (String category : DB.getCategories()) {
                                %>
                                <option><%=category%></option>
                                <%                            }
                                %>
                            </select>
                            <h4>Tags (Separated by a comma):</h4> <input id ="addPinEditTags" type="text" class ="input-xlarge" placeholder="ferrari, dynamite fishing, yolo">
                            <input type ="hidden" id="addPinEditX">
                            <input type ="hidden" id="addPinEditY">
                        </center>
                    </div>
                    <div class="modal-footer">
                        <center>
                            <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
                            <button class="btn btn-success" onClick ="addNewPin($('#addPinEditInfo').val(), $('#addPinEditCategory').val(),
                                $('#addPinEditTags').val(), $('#addPinEditX').val(), $('#addPinEditY').val());">Add Pin</button>
                        </center>
                    </div>
                </div>

                <!-- Open User Modal -->
                <script>
                    var currentViewedUser;
                    function openUserModal(username) {
                        $.ajax({
                            type: 'POST',
                            url: '/LifeBook/GetUserFromUsernameServlet',
                            data: {
                                username: username
                            },
                            success: function(msg) {
                                var user = eval("(" + msg + ")");
                                $("#userModalProfileLink").attr("href", "users/" + user.username);
                                $("#userModalImage").attr("src", "userimages/" + user.username);
                                $("#userModalUsername").html(user.username);
                                $("#userModalAboutMe").html(user.aboutme);
                                currentViewedUser = user.username;

                                if ('<%=user.getUsername()%>' === user.username)
                                    $('#followUserButton').hide();
                                else
                                    $('#followUserButton').show();

                                if (user.userIsLikedByCurrentUser) {
                                    $('#isFollowingUserSpan').html("(" + user.followerCount + ") Following");
                                    $('#userLikeIcon').addClass("icon-white");
                                    $('#followUserButton').addClass("btn-danger");
                                    $('#followUserButton').addClass("active");
                                } else {
                                    $('#isFollowingUserSpan').html("(" + user.followerCount + ") Follow");
                                    $('#userLikeIcon').removeClass("icon-white");
                                    $('#followUserButton').removeClass("btn-danger");
                                    $('#followUserButton').removeClass("active");
                                }
                            }
                        });

                        $('#userModal').modal('show');
                    }
                </script>

                <!-- User follows another user -->
                <script>
                    function followUser() {
                        $.ajax({
                            type: 'POST',
                            url: '/LifeBook/FollowUserServlet',
                            data: {
                                user: currentViewedUser,
                                currentUser: '<%=user.getUsername()%>'
                            },
                            success: function(msg) {
                                var user = eval("(" + msg + ")");
                                if (user.userIsLikedByCurrentUser) {
                                    $('#isFollowingUserSpan').html("(" + user.followerCount + ") Following");
                                    $('#userLikeIcon').addClass("icon-white");
                                    $('#followUserButton').addClass("btn-danger");
                                    $('#followUserButton').addClass("active");
                                } else {
                                    $('#isFollowingUserSpan').html("(" + user.followerCount + ") Follow");
                                    $('#userLikeIcon').removeClass("icon-white");
                                    $('#followUserButton').removeClass("btn-danger");
                                    $('#followUserButton').removeClass("active");
                                }
                            }
                        });
                    }
                </script>

                <!-- Open Image Modal-->
                <script>
                    var currentImageID;
                    var isEditMode = new Boolean();
                    function openImageModal(imageID, imageWidth, imageHeight, imageTitle, imageCaption, imageLikes, imageOwner) {
                        var imageSource = "images/" + imageID;
                        $("#viewTitle").html(imageTitle);
                        $("#viewCaption").html(imageCaption);
                        $("#viewUser").html("by " + imageOwner);
                        $("#likeCounter").html(imageLikes);
                        if (imageOwner === '<%=user.getUsername()%>') {
                            $("#deleteButton").show();
                        } else {
                            $("#deleteButton").hide();
                        }
                        currentImageID = imageID;
                        isEditMode = '<%=user.getUsername()%>' === imageOwner;

                        $("#openUserButton").attr("onClick", 'openUserModal("' + imageOwner + '")');

                        likeImage(false);
                        updateCanvasImage(imageSource, imageWidth, imageHeight);

                        $('#imageViewModal').modal('show');
                    }

                    function updateCanvasImage(imageSource, imageWidth, imageHeight) {
                        var source = imageSource;
                        var width = imageWidth;
                        var height = imageHeight;
                        initCanvas("imageCanvas", source, width, height, false, isEditMode);
                        loadPins(currentImageID);
                    }
                </script>

                <!-- Delete Image -->
                <script>
                    function deletePhoto() {
                        $.ajax({
                            type: 'POST',
                            url: '/LifeBook/DeleteImageServlet',
                            data: {
                                imageID: currentImageID
                            },
                            success: function(msg) {
                                //var result = eval("(" + msg + ")");
                                location.reload();
                            }
                        });
                    }
                </script>

                <!-- Upload Image -->
                <script>
                    function uploadImage() {
                        var uploadTitle = $("#uploadTitle").val();
                        var uploadCaption = $("#uploadCaption").val();
                        var pinData = sessionStorage.getItem("pinData");

                        $.ajax({
                            type: 'POST',
                            url: '/LifeBook/UpdateUploadedImageServlet',
                            data: {
                                uploadTitle: uploadTitle,
                                uploadCaption: uploadCaption,
                                pinData: pinData
                            },
                            success: function(msg) {
                                //var result = eval("(" + msg + ")");
                                sessionStorage.removeItem("pinData");
                                location.reload();
                            }
                        });

                    }
                </script>

                <!-- Like Image -->
                <script>
                    function likeImage(updateDatabase) {
                        $.ajax({
                            type: 'POST',
                            url: '/LifeBook/UserLikesAnImage',
                            data: {username: '<%=user.getUsername()%>', imageID: currentImageID, updateDatabase: updateDatabase},
                            success: function(msg) {
                                var result = eval("(" + msg + ")");
                                if (result.imageIsLikedByUser) {
                                    $('#likeIcon').addClass("icon-white");
                                    $('#viewLikeButton').addClass("btn-danger");
                                    $('#viewLikeButton').addClass("active");
                                } else {
                                    $('#likeIcon').removeClass("icon-white");
                                    $('#viewLikeButton').removeClass("btn-danger");
                                    $('#viewLikeButton').removeClass("active");
                                }
                                $('#likeCounter').html(result.likeCount);
                            }
                        });
                    }
                </script>
                <script src="js/jquery.js"></script>
                <script src="bootstrap/js/bootstrap.js"></script>
                <script src="js/masonry.pkgd.min.js"></script>
                <script src="js/imagesloaded.pkgd.js"></script>
                <script src="js/kinetic-v4.5.5.min.js"></script> 
                <script src="js/imageTagging.js"></script>
                <script>
                    var container = document.querySelector('#myMasonryContainer');
                    var msnry;
                    // initialize Masonry after all images have loaded
                    imagesLoaded(container, function() {
                        msnry = new Masonry(container);
                    });
                </script>
                </body>
                </html>